package org.stars.dao.sqlmapper.macro;

import java.util.List;

import org.stars.config.Message;
import org.stars.dao.exception.parser.CircularDependencyException;
import org.stars.dao.exception.parser.SqlNotDefinedException;
import org.stars.dao.sqlmapper.SqlDefinition;
import org.stars.dao.sqlmapper.SqlMacro;
import org.stars.dao.sqlmapper.SqlMapper;

@MacroDefinition(evaluation=MacroEvaluation.SOURCE_PROCESSING, arguments=MacroParam.REQUIRED)
public class Include extends MacroBase {

	@Override
	public ReturnState execute(SqlMapper sqlMapper, SqlDefinition sqlQuery, SqlMacro sqlMacro) throws Exception {
		List<String> args=sqlMacro.getArgs();
		String include=args.get(0);

		if (include.equalsIgnoreCase(sqlQuery.getId()))
		{
			String msg=Message.CIRCULAR_DEPENDENCY_ERROR.with(include, sqlQuery.getId() ,sqlMapper.getId());
			log.error(msg);
			throw(new CircularDependencyException(msg));
		}
		
		SqlDefinition origin=sqlMapper.getMap().get(include);
		if (origin==null)
		{
			String msg=Message.SQL_NOT_DEFINED_ERROR.with(include, sqlQuery.getId() ,sqlMapper.getId());
			log.error(msg);
			throw(new SqlNotDefinedException(msg));
		}
		
		SqlDefinition def=origin.clone();		
		
		sqlMacro.setTemplateText(def.getTemplateText());
		sqlMacro.setParts(def.getParts());
		
		return ReturnState.EVALUATE_PARTS;		
	}

}
